package com.jswzc.common.api.service.emailUnified;


import com.jswzc.api.service.emailUnified.EmailUnifiedServiceI;
import com.jswzc.framework.util.emailUtil.ApacheMailUtil;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by DeathCat on 2017/05/12.
 */
@Service("emailUnifiedService")
public class EmailUnifiedServiceImpl implements EmailUnifiedServiceI {



    @Override
    public Map<String, Object> sendEmail(String addTo,String addFrom,String sub,String msg,String smtpType,String username,String password,String port) throws Exception {
        Map<String, Object> res = new HashMap<String, Object>();
        res.put("res", "F");
        res.put("msg", "未知错误");
        boolean b = true;
        if (isNullOrEmpty(addTo)) {
            res.put("msg", "邮件送达地址：addTo字段不可为空");
            b = false;
        }
        if (isNullOrEmpty(addFrom)) {
            res.put("msg", "邮件发送方地址：addFrom字段不可为空");
            b = false;
        }
        if (isNullOrEmpty(sub)) {
            res.put("msg", "邮件标题：sub字段不可为空");
            b = false;
        }
        if (isNullOrEmpty(msg)) {
            res.put("msg", "邮件内容：msg字段不可为空");
            b = false;
        }
        if (isNullOrEmpty(smtpType)) {
            res.put("msg", "邮件服务商类型：type字段不可为空");
            b = false;
        }
        if (isNullOrEmpty(username)) {
            res.put("msg", "邮件发送服务器用户名：username字段不可为空");
            b = false;
        }
        if (isNullOrEmpty(password)) {
            res.put("msg", "邮件发送服务器密码：password字段不可为空");
            b = false;
        }
        if (isNullOrEmpty(port)) {
            res.put("msg", "邮件发送服务器SMTP端口号：port字段不可为空");
            b = false;
        }

        if (b) {
            try {
                String utilres=ApacheMailUtil.sendEmail(addTo,addFrom,sub,msg,smtpType,username,password,Integer.parseInt(port+""));
                if(utilres.equals("T")){
                    res.put("res", "T");
                    res.put("msg", "发送成功");
                }else{
                    res.put("msg", utilres);
                }

            } catch (Exception e) {
                res.put("msg", "未知错误:" + e.getMessage());
            }
        }
        return res;
    }




    public static boolean isNullOrEmpty(Object obj) {
        return obj == null || "".equals(obj.toString());
    }


}
